import time

from django.shortcuts import render, redirect

# Create your views here.
from golf import models
from golf.form import MemberModelForm


def memberList(req):
    list = models.memberinfo.objects.all()
    return render( req, "golf_member_info.html",{"list":list})


def memberAdd(req):
    if req.method == "POST":
        form = MemberModelForm( data=req.POST )
        if form.is_valid():
            form.save()
            return redirect( "/golf/memberList/" )
    form = MemberModelForm()
    return render( req, "golf_member_add.html",{"memberInfo":form})


def memberEdit(req,nid):
    if req.method == "POST":
        info = models.memberinfo.objects.filter(id=nid).first()
        form = MemberModelForm( data=req.POST, instance=info )
        if form.is_valid():
            form.save()
            return redirect( "/golf/memberList/" )
    info = models.memberinfo.objects.filter(id=nid).first()
    form = MemberModelForm( instance=info )
    return render( req, "golf_member_edit.html",{"form": form})

def charge(req,nid):
    if req.method == "POST":
        newbalance  = req.POST.get( "newbalance" )
        balance = models.memberinfo.objects.filter(id = nid).first().balance
        temp = int(balance) + int(newbalance)
        models.balanceinfo.objects.create(balance = balance,newbalance=newbalance,member_id=nid)
        models.memberinfo.objects.filter(id = nid).update(balance = str(temp))
        return redirect( "/golf/memberList/" )
    info = models.memberinfo.objects.filter( id=nid ).first()
    return render( req, "golf_member_charge.html",{"memberinfo":info} )

def info(req,nid):
    sales = models.saleinfo.objects.filter(member_id= nid)
    balance = models.balanceinfo.objects.filter(member_id=nid)
    return render( req, "golf_member_infos.html",{"sales":sales,"balance":balance})

def send(req,nid):
    indo = models.memberinfo.objects.filter(id=nid).first()
    phone = indo.phone
    name = indo.name
    balance = indo.balance
    sendMails(phone,name,balance)
    return redirect("/golf/memberList/")

def sendMails(phone,name,balance):
    ##发送会员余额
    import requests
    import json

    appid = '89472'  # SUBMAIL控制台创建appid
    appkey = '7ee3d241285a0a490eef2210491a1dca'  # SUBMAIL控制台获取appkey
    project = 'naBHs2'  # SUBMAIL控制台创建模板 获取模板id
    to = phone  # 手机号码

    url = 'https://api-v4.mysubmail.com/sms/xsend.json'

    header = {"Content-type": "application/json"}
    vars = {
        'name': name,
        'num2': balance  # time为参数名 和模板中参数名一致
    }
    param = {
        'appid': appid,
        'signature': appkey,
        'project': project,
        'to': to,
        'vars': json.dumps( vars )
    }
    res = requests.post( url, data=json.dumps( param ), headers=header )
    print( res.json() )
    return True